package top.mypath.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import lombok.RequiredArgsConstructor;
import top.mypath.model.MaxOrderCombine;
import top.mypath.model.Order;
import top.mypath.model.vo.OrderVO;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 对账服务
 *
 * @author LiYalin
 */
@RequiredArgsConstructor
public class ReconciliationService {

    private final SplitService splitService;

    /**
     * 对对账订单进行发票拆分
     * @param checkingFieldPath
     * @param quota
     * @return
     */
    public List<OrderVO> orderInvoiceSplit(String checkingFieldPath, BigDecimal quota) {
        splitService.setQuota(quota);
        OrderExcelListener orderExcelListener = new OrderExcelListener();
        // 这里默认读取第一个sheet
        EasyExcel.read(checkingFieldPath, Order.class, orderExcelListener).sheet().doRead();
        List<Order> cachedDataList = orderExcelListener.getCachedDataList();
        List<MaxOrderCombine> maxOrderCombines = splitService.splitData(cachedDataList);
        Map<String, OrderVO> orderMap = cachedDataList.stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtil.copyProperties(order, orderVO);
            return orderVO;
        }).collect(Collectors.toMap(OrderVO::getBatchNumber, Function.identity()));
        for (MaxOrderCombine orderCombine : maxOrderCombines) {
            String invoiceSerialNumber = orderCombine.getInvoiceSerialNumber();
            List<String> batchNumbers = orderCombine.getBatchNumbers();
            for (String batchNumber : batchNumbers) {
                orderMap.get(batchNumber).setInvoiceSerialNumber(invoiceSerialNumber);
            }
        }
        cachedDataList.clear();
        return new ArrayList<>(orderMap.values());
    }


}
